import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/Login.vue'
import Home from './components/Home.vue'
import Welcome from './components/Welcome.vue'
import Users from './components/User/Users.vue'

Vue.use(Router)

//  应为全局守卫需要用到router.beforeEach 所以需要定义一个变量router接收路由规则 然后再暴露出去
const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home', component: Home, redirect: '/welcome', children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  //  如果是直接访问的login页面则正常执行login.vue里的逻辑
  if (to.path === '/login') return next()
  //  定义一个变量token   获取sessionStorage里的token  如果没获取到(sessionStorage里没有token --- 则代表没有登录) 就直接跳到/login页面
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
